<template>
  <div class="editArticle">

    <a-form-item label="标题" required>
      <a-input v-model="article.title" size="large" />
    </a-form-item>

    <a-form-item label="内容" required>
      <client-only>
        <mavon-editor
          v-model="article.content"
          placeholder="开始创作吧..."
          :shortCut="false"
          codeStyle="atom-one-dark"
          ref="mavon"
          style="z-index: 0;min-height: 800px;margin-top: 10px"
          @imgAdd="imageAdd"
          @imgDel="imageRemove"
        />
      </client-only>
    </a-form-item>

    <!--文章配图-->
    <a-form-item label="文章配图" required>
      <a-row :gutter="20">
        <a-col :xs="24" :sm="12" :lg="12" :xl="12" :xxl="12">
          <img :src="article.imgUrl" alt="" style="height: 120px;width: 100%">
        </a-col>
        <a-col :xs="24" :sm="12" :lg="12" :xl="12" :xxl="12">
          <a-upload-dragger
            name="article-image"
            :action="uploadUrl"
            :remove="removeImage"
            @change="handleChange">
            <p class="ant-upload-drag-icon"><a-icon type="inbox" /></p>
            <p class="ant-upload-text">点击或者拖拽图片上传</p>
          </a-upload-dragger>
        </a-col>
      </a-row>
    </a-form-item>

    <!-- 选择项-->
    <a-row :gutter="20">
      <a-col :xs="24" :sm="8" :xl="8" :xxl="8">
        <a-form-item label="类型" >
          <a-select v-model="article.type" size="large" placeholder="选择分类...">
            <a-select-option :value="0">原创</a-select-option>
            <a-select-option :value="1">转载</a-select-option>
          </a-select>
        </a-form-item>

      </a-col>
      <a-col :xs="24" :sm="8" :xl="8" :xxl="8">
        <a-form-item label="分类" >
          <a-select
            v-model="article.category"
            size="large"
            allowClear
            placeholder="选择分类...">
            <a-select-option :value="item" v-for="(item, index) in items" :key="index">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-item>

      </a-col>
      <a-col :xs="24" :sm="8" :xl="8" :xxl="8">
        <a-form-item label="标签" >
          <a-select
            v-model="article.tags"
            size="large"
            allowClear
            mode="multiple"
            placeholder="选择标签...">
            <a-select-option :value="item" v-for="(item, index) in items" :key="index">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-item>

      </a-col>
    </a-row>

    <!--描述-->
    <a-form-item label="描述">
      <a-textarea
        v-model="article.abstract"
        allowClear
        :rows="4"
        placeholder="文章描述(1-150)个字符"/>
    </a-form-item>

    <a-form-item style="text-align: center">
      <a-button type="primary" size="large" ghost shape="round" @click="changeArticle">修改</a-button>
    </a-form-item>
  </div>
</template>

<script>
  import app from "../../../../app"
  import moment from "moment";
  const uploadUrl = `${app.api}/api/${app.apiVersion}/admin/articleImage/`
  export default {
    name: "edit",
    layout: "admin",
    head(){ return { title: `编辑 - ${this.article.title} - ${app.name}` } },
    async asyncData({ $axios, store, query, error }) {
      let url = `${app.api}/api/${app.apiVersion}/admin/article/`;
      const resp = await $axios.$get(url, { params: { uuid: query.uuid }});
      let article = resp.code === 200 ? resp.data : {};
      article.tags = article.tags.split(",")
      return { article }
    },
    data:()=>({
      uploadUrl,
      items: [
        "python",
        "css",
        "nuxt",
        "vue",
        "mysql",
        "golang",
        "python3",
        "redis",
        "html",
        "web",
        "life",
        "linux",
        "ubuntu",
        "centos",
        "nodejs",
        "js",
        "typescript",
        "生活",
        "框架",
        "感悟",
        "前端",
        "后端",
        "资讯",
        "开发工具",
        "小技巧",
        "教程",
        "优化",
        "面试",
        "公众号",
        "设计模式",
        "vuetify",
        "echo",
        "小程序",
        "AI",
        "工具",
        "chrome",
        "fireFox",
        "数据库",
        "服务器",
        "UI",
        "正则表达式",
        "gorm",
        "jwt",
        "json",
        "nginx"
      ],
    }),
    methods: {
      imageAdd(pos, file) {
        let formdata = new FormData();
        formdata.append('article-image', file);
        this.$axios.$post(uploadUrl, formdata)
          .then((res)=>{
            if (res.code === 200 ) {
              this.$refs.mavon.$img2Url(pos, res.data);
              this.$message.success("添加图片成功")
            }else {
              this.$message.error("添加图片失败")
            }
          }).catch((error)=>{
          this.$message.error(error)
        })
      },
      imageRemove (filename) {
        this.$axios.$delete(uploadUrl, { data: { name: filename[0] } })
          .then((res)=>{
            if (res.code === 200) {
              this.$message.success("移除图片成功")
            }else {
              this.$message.warning("移除图片失败")
            }
          }).catch((error)=>{
          this.$Message.error(error)
        })
      },
      handleChange(info) {
        const status = info.file.status;
        if (status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (status === 'done') {
          this.article.imgUrl = info.file.response.data;
          this.$message.success(`${info.file.name} 上传成功`);
        } else if (status === 'error') {
          this.$message.error(`${info.file.name} 上传失败`);
        }
      },
      // 文章封面
      removeImage (file, fileList) {
        this.$axios.$delete(uploadUrl, { data: { name: this.article.imgUrl } })
          .then((res)=>{
            if (res.code === 200) {
              this.article.imgUrl = "";
              this.$message.success("移除图片成功")
            }else {
              this.$message.warning("移除图片失败")
            }
          }).catch((error)=>{
          this.$message.error(error)
        })
      },
      changeArticle(e){
        let url = `${app.api}/api/${app.apiVersion}/admin/article/`;
        if (!this.article.imgUrl){
          this.$message.warning("文章配图不允许为空!")
        }else {
          this.article.author = this.$store.state.user.username;
          this.$axios.$put(url, this.article)
            .then((resp)=>{
              console.log(resp)
              if (resp.code === 200) {
                this.$message.success(resp.msg)
                this.$router.push({path:"/admin/article/list/"})
              }else {
                this.$message.warning(resp.msg)
              }
            }).catch((error)=>{
              // TODO 前端错误处理
          })
        }
      }
    }
  }
</script>

<style scoped>

</style>
